/**
 * 
 */
package stc.skymobi.content.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import stc.skymobi.content.MutableContent;


/**
 * @author hp
 *
 */
public class DefaultContent implements MutableContent {

    private static final Logger logger = LoggerFactory.getLogger(DefaultContent.class);
    
    protected String  name;
    protected byte[]  data;
    protected Date    lastModified;
    protected byte[]  md5;

    public DefaultContent() {
    }
    
    public void initData(byte[] bytes) {
        data = bytes.clone();
        
        MessageDigest md5inst;
        try {
            md5inst = MessageDigest.getInstance( "MD5" );
            md5inst.update( data );
            md5 = md5inst.digest();
        } catch (NoSuchAlgorithmException e) {
        	logger.error("initData:", e);
        }
    }
    
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    
    public void setLastModified(Date lastModified) {
        this.lastModified = new Date(lastModified.getTime());
    }
    
    /* (non-Javadoc)
     * @see com.skymobi.content.Content#getInputStream()
     */
    public InputStream getInputStream() {
        return new ByteArrayInputStream(data);
    }

    /* (non-Javadoc)
     * @see com.skymobi.content.Content#getLastModified()
     */
    public Date getLastModified() {
        return new Date(lastModified.getTime());
    }

    /* (non-Javadoc)
     * @see com.skymobi.content.Content#getMD5()
     */
    public byte[] getMd5() {
        return md5.clone();
    }

    public String getMd5AsString() {
        StringBuilder sb = new StringBuilder();
        for (byte b : md5) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public String getName() {
        return name;
    }

    public int getSize() {
        return data.length;
    }

    @Override
    public String toString() {
        ToStringBuilder builder = new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE);
        return  builder.append("name", name)
                .append("size", (null != data ? data.length : 0) )
                .append("lastModified", lastModified)
                .append("md5", getMd5AsString())
                .toString();
    }

}
